import yt_dlp
from pathlib import Path

def download_bili_audio(url: str, output_dir: str = "downloads") -> dict:
    """
    下载B站视频的音频并转换为MP3
    
    Args:
        url: B站视频URL
        output_dir: 输出目录
        
    Returns:
        下载结果字典
    """
    # 创建输出目录
    Path(output_dir).mkdir(exist_ok=True)
    
    # 简单配置：仅下载音频
    ydl_opts = {
        'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    
    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
            
        return {
            'success': True,
            'message': '音频下载成功'
        }
    except Exception as e:
        return {
            'success': False,
            'error': str(e)
        }


if __name__ == "__main__":
    # 测试
    test_url = "https://www.bilibili.com/video/BV1i9snzPEDq"
    
    print("开始下载音频...")
    result = download_bili_audio(test_url)
    
    if result['success']:
        print("✅ 音频下载成功!")
    else:
        print(f"❌ 下载失败: {result['error']}")